﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;

[System.Serializable]
public class BestScore
{
    public List<int> scores;
}


public class SaveScore : MonoBehaviour
{
    //定义需要保存的分数的数量
    [SerializeField]
    public int saveScoreNum;

    //保存文件名
    [SerializeField]
    private string scoreFileName;

    //最高分记录
    public List<int> historyBestScore;

    //存储当前得分
    public int currentScore;

    // Start is called before the first frame update
    void Start()
    {
        loadBestScore();

        //GlobalEventManager.OnScoreChange += s => { currentScore = s; };
        GlobalEventManager.OnGameOver += saveBestScore;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //保存历史最高分
    public void saveBestScore()
    {
        //将当前分数写入排行榜并排序
        if(currentScore != 0)
        {

        
        historyBestScore.Add(currentScore);
        historyBestScore.Sort();
        historyBestScore.Reverse();

        if(historyBestScore.Count > saveScoreNum)
        {
            historyBestScore.RemoveAt(saveScoreNum);
        }

        //将排行榜数据保存到JSON文件中
        BestScore bestScore = new BestScore();
        bestScore.scores = historyBestScore;
        string Json = JsonUtility.ToJson(bestScore);
        File.WriteAllText(Application.persistentDataPath + scoreFileName, Json);


        }
    }



    //读取历史最高分
    public void loadBestScore()
    {
        historyBestScore.Clear();
        if(File.Exists(Application.persistentDataPath + scoreFileName))
        {
            StreamReader reader = new StreamReader(Application.persistentDataPath + scoreFileName);
            BestScore bestScore = JsonUtility.FromJson<BestScore>(reader.ReadToEnd());
            reader.Close();

            if(bestScore.scores.Count <= saveScoreNum)
            {
                historyBestScore = bestScore.scores;
            }
            else
            {
                for (int i = 0; i < saveScoreNum; i++)
                {
                    historyBestScore.Add(bestScore.scores[i]);
                }
            }
        }
        else
        {
            BestScore bestScore = new BestScore();
            string Json = JsonUtility.ToJson(bestScore);
            File.WriteAllText(Application.persistentDataPath + scoreFileName, Json);
        }
    }
}
